<template>
  <div class="mall-layout">
    <!-- 仅商城页面显示：顶部导航栏 -->
    <TopNav 
      :current-tab="currentTab"
      :nav-items="navItems"
      @tab-change="handleTabChange"
      @icon-click="handleIconClick"
    />
    
    <!-- 商城子页面内容（推荐/犬牌/保险页） -->
    <router-view class="mall-content" />
  </div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import TopNav from '../mall/TopNav.vue';

// 商城标签与路由的映射
const tabRouteMap = [
  { tabName: '推荐', routeName: 'recommend', path: '/mall/recommend' },
  { tabName: '犬牌', routeName: 'dogTag', path: '/mall/dog-tag' },
  { tabName: '保险', routeName: 'insurance', path: '/mall/insurance' },
  { tabName: '流量', routeName: 'traffic', path: '/mall/traffic' },
];

const navItems = ref(tabRouteMap.map(item => item.tabName));
const currentTab = ref(0);
const route = useRoute();
const router = useRouter();

// 根据当前路由设置激活的标签
const setTabByRoute = () => {
  const currentRouteName = route.name;
  const matchedIndex = tabRouteMap.findIndex(item => item.routeName === currentRouteName);
  if (matchedIndex !== -1) {
    currentTab.value = matchedIndex;
  }
};

// 标签点击：切换路由
const handleTabChange = (index) => {
  const targetRoute = tabRouteMap[index];
  router.push(targetRoute.path);
};

// 右侧图标点击事件
const handleRightIconClick = () => {
  console.log('商城页面：右侧笔记图标点击');
};

// 监听路由变化，同步更新标签激活状态
watch(() => route.name, setTabByRoute);

onMounted(() => {
  setTabByRoute();
  // 确保初始显示推荐页
  if (route.path === '/mall') {
    router.push('/mall/recommend');
  }
});
</script>

<style scoped>
.mall-layout {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 60px; /* 添加底部内边距，确保内容完整显示 */
}

.mall-content {
  padding: 0 16px;
  max-width: 600px;
  margin: 0 auto;
  min-height: calc(100vh - 140px); /* 确保内容区域有足够高度 */
}
</style>